package com.example.lenovo.asia5b.commodity.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.example.lenovo.asia5b.my.order.bean.ParcelListBean;
import com.wushi.lenovo.asia5b.R;

import org.json.JSONObject;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import app.BaseActivity;
import fay.frame.ui.U;
import com.example.lenovo.asia5b.ui.DownloadPicture;
import com.example.lenovo.asia5b.ui.LoadingDalog;
import com.example.lenovo.asia5b.ui.MyRatingBar;
import com.example.lenovo.asia5b.util.ICallBack;
import com.example.lenovo.asia5b.util.JsonTools2;
import com.example.lenovo.asia5b.util.Logic;
import com.example.lenovo.asia5b.util.MD5;
import com.example.lenovo.asia5b.util.Setting;

import static com.wushi.lenovo.asia5b.R.id.btn_next_step;
import static com.wushi.lenovo.asia5b.R.id.public_btn_left;
import static com.example.lenovo.asia5b.util.SharedPreferencesUtils.getUserBean;

/**
 * 包裹评价
 * Created by lenovo on 2017/8/8.
 */

public class AddEvalutatActivity extends BaseActivity  implements ICallBack{
    private ParcelListBean bean;
    private String order_id,rec_id;
    private MyRatingBar bar_one,bar_two,bar_three;
    private List<String> imagsPaths = null;
    private List<LinearLayout> linearLayouts ;
    private  int position;
    private LoadingDalog loadingDalog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_evalutat);
        initView();
    }

    public void initView() {
        loadingDalog = new LoadingDalog(AddEvalutatActivity.this);
        Intent intent = this.getIntent();
        bean = (ParcelListBean)intent.getSerializableExtra("bean");
        order_id = getIntent().getStringExtra("order_id");
        rec_id= getIntent().getStringExtra("rec_id");
        F.id(R.id.public_title_name).text(getResources().getString(R.string.comment));
        F.id(public_btn_left).clicked(this);
//        F.id(R.id.txt_parcel_number).text(bean.rec_id);
//        F.id(R.id.txt_order_number).text(order_id);
        F.id(R.id.txt_name).text(bean.goods_name);
        F.id(R.id.txt_price).text(bean.goods_price);
        F.id(R.id.txt_num).text("x"+bean.goods_number);
        F.id(btn_next_step).clicked(this);
        DownloadPicture.loadNetwork(bean.goods_attr_thumb,F.id(R.id.image_name).getImageView());

        bar_one = (MyRatingBar)findViewById(R.id.bar_one);
        bar_two = (MyRatingBar)findViewById(R.id.bar_two);
        bar_three = (MyRatingBar)findViewById(R.id.bar_three);

        F.id(R.id.txt_bar_one).text(5 + getResources().getString(R.string.xcp));
        F.id(R.id.txt_bar_two).text(5 + getResources().getString(R.string.xcp));
        F.id(R.id.txt_bar_three).text(5 + getResources().getString(R.string.xcp));
        bar_one.setTextView(F.id(R.id.txt_bar_one).getTextView());
        bar_two.setTextView(F.id(R.id.txt_bar_two).getTextView());
        bar_three.setTextView(F.id(R.id.txt_bar_three).getTextView());

        linearLayouts = new ArrayList<LinearLayout>();
        imagsPaths = new ArrayList<String>();
        linearLayouts.add((LinearLayout) F.id(R.id.ll_one).getView());
        linearLayouts.add((LinearLayout) F.id(R.id.ll_two).getView());
        linearLayouts.add((LinearLayout) F.id(R.id.ll_three).getView());
        linearLayouts.add((LinearLayout) F.id(R.id.ll_four).getView());
        linearLayouts.add((LinearLayout) F.id(R.id.ll_five).getView());
        for (int i = 0; i<linearLayouts.size(); i++){
            imagsPaths.add("");
            LinearLayout layout = linearLayouts.get(i);
            layout.setOnClickListener(new StartPhotOnOnClick(i));
            layout.getChildAt(1).setOnClickListener(new DelImageOnOnClick(i));

        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case public_btn_left:
                finish();
                break;
            case btn_next_step:
                addEvalutatData();
                break;

        }
    }

    /**
     * 提交评论
     */
    public void  addEvalutatData() {
        //商品相似
        String desc_rank   = bar_one.getRating()+"";
        //物流速度
        String rate_rank = bar_two.getRating()+"";
        //服务态度
        String service_rank = bar_three.getRating()+"";
        //相符描述
        String content = F.id(R.id.edit_explain).getText().toString();
        //图片集
        String imgs  = "";
//        if (TextUtils.isEmpty(content)) {
//            U.Toast(AddEvalutatActivity.this,getResources().getString(R.string.smbnwk));
//            return;
//        }
            try {
                loadingDalog.show();
                for (int i = 0; i < imagsPaths.size();i++){
                    if (!TextUtils.isEmpty(imagsPaths.get(i))) {
                        imgs = imgs + imagsPaths.get(i) +",";
                    }
                }
                if (imgs .length() > 5) {
                    imgs = imgs.substring(0,imgs.length()-1);
                }
                Map<String, String> parmaMap = new HashMap<String, String>();
                String url = Setting.ORDER_COMMENT;
                String user_id = getUserBean().user_id;
                Date date = new Date();
                String time = String.valueOf(date.getTime());
                String[] sort = {"user_id" + user_id, "rec_id" + rec_id,"content" + content, "time" + time};
                String sortStr = Logic.sortToString(sort);
                String md5_32 = MD5.MD5EncryptionFor32(MD5.MD5EncryptionFor32(sortStr));//二次加密
                parmaMap.put("user_id", user_id);
                parmaMap.put("rec_id", rec_id);
                parmaMap.put("content", content);
                parmaMap.put("desc_rank", desc_rank);
                parmaMap.put("rate_rank", rate_rank);
                parmaMap.put("service_rank", service_rank);
                parmaMap.put("time", time);
                parmaMap.put("sign", md5_32);
                Map<String, String> parmaMap2 = new HashMap<String, String>();
                parmaMap2.put("cmmt_imgs", imgs);
                JsonTools2.dataHttps(this, url, parmaMap,parmaMap2, 0);
            } catch (Exception e) {
            }
    }

    private Handler handler2 = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            JSONObject result= null;
            try {
                result = new JSONObject(msg.obj.toString());
            } catch (Exception e) {
            }
            int action = msg.what;
            if (action == 0) {
                if (null != result && result instanceof JSONObject) {
                    try {
                        JSONObject jsonObect = (JSONObject) result;
                        int state = jsonObect.getInt("State");
                        if (state == 0) {
                            U.Toast(AddEvalutatActivity.this, getResources().getString(R.string.cg));
                            Intent intent = new Intent();
                            intent.putExtra("222", 2222);
                            AddEvalutatActivity.this.setResult(0, intent);
                            finish();
                        }
                        else if (state == 1) {
                            U.Toast(AddEvalutatActivity.this, getResources().getString(R.string.qmsb));
                        } else if (state == 2) {
                            U.Toast(AddEvalutatActivity.this, getResources().getString(R.string.cscw));
                        } else if (state == 3) {
                            U.Toast(AddEvalutatActivity.this, getResources().getString(R.string.wdl));
                        } else if (state == 4) {
                            U.Toast(AddEvalutatActivity.this, getResources().getString(R.string.nyplggsp));
                        }
                    } catch (Exception e) {
                    }
                }
                loadingDalog.dismiss();
            }
        }
    };

    @Override
    public void logicFinish(Object result, int action) {
        Message msg = new Message();
        msg.what = action;
        msg.obj = result.toString();
        handler2.sendMessage(msg);

    }

    public class StartPhotOnOnClick implements View.OnClickListener {
        int id;
        public StartPhotOnOnClick(int id) {
            this.id = id;
        }
        @Override
        public void onClick(View v) {
            loadingDalog.showPhoto();
            position = id;
        }
    }

    public class DelImageOnOnClick implements View.OnClickListener {
        int id;
        public DelImageOnOnClick(int id) {
            this.id = id;
        }
        @Override
        public void onClick(View v) {
            ((ImageView)linearLayouts.get(id).getChildAt(0)).setImageResource(R.drawable.main_remaishangpin);
            imagsPaths.set(id,"");
        }
    }

    Uri cameraUri = null;
    @Override
    protected void onActivityResult(int requestCode, int arg1, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, arg1, data);
        switch (requestCode) {
            case 101:// 相机
//                listPicture.clear();
                if (data != null) {
                    if (data.getExtras() != null) {
                        cameraUri = loadingDalog.getPhotoUrihotoUri();
                        hear(null);
                    } else {
                        U.Toast(this,getResources().getString(R.string.system_no_getpic));
                    }
                } else {
                    if (loadingDalog.getPhotoUrihotoUri() != null) {
                        cameraUri = loadingDalog.getPhotoUrihotoUri();
                        hear(null);
                    } else {
                        U.Toast(this,getResources().getString(R.string.system_no_getpic));
                    }
                }
                // setPicture();
                break;
            case 102:// 相册返回
//                listPicture.clear();
                cameraUri = null;
                if (data != null) {
                    if (data.getData() != null) {
                        cameraUri = data.getData();
                        hear(null);
                    } else {
                        U.Toast(this, getResources().getString(R.string.system_no_getpic));
                    }
                }else if (loadingDalog.getPhotoUrihotoUri() != null) {
                    cameraUri = loadingDalog.getPhotoUrihotoUri();
                    hear(null);
                } else {
                    U.Toast(this, getResources().getString(R.string.system_no_getpic));
                }
                break;
            case 103:
                break;
        }
    }

    public void hear(Intent data) {
        Bitmap photo = null;
        if (data != null) {
            Bundle bundle = data.getExtras();
            if (bundle != null) {
                photo = bundle.getParcelable("data");
            } else if (data != null) {
                Uri uri1 = data.getData();
                try {
                    photo = MediaStore.Images.Media.getBitmap(getContentResolver(), uri1);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } else {
            try {
                photo = MediaStore.Images.Media.getBitmap(getContentResolver(), cameraUri);
                //图片太大实现压缩功能
                if (DownloadPicture.getBitmapSize(photo) > 10000000) {
                    photo = DownloadPicture.smallOneFifth(photo);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (photo == null) {
            return;
        }
        BufferedOutputStream bos = null;
        if (photo != null) {
            File dirFile = new File(Setting.IMAGE_ROOTPATH);
            if (!dirFile.exists())
                dirFile.mkdirs();
            SimpleDateFormat sDateFormat = new SimpleDateFormat(
                    "yyyyMMddhhmmss", Locale.ENGLISH);
            File uploadFile = new File(dirFile + "/"
                    + sDateFormat.format(new java.util.Date())
                    + ".jpg");

            char[] chars = "0123456789abcdef".toCharArray();
            StringBuilder sb = new StringBuilder("");
            int bit;
            try {
                uploadFile.createNewFile();
                bos = new BufferedOutputStream(new FileOutputStream(uploadFile));
                photo.compress(Bitmap.CompressFormat.JPEG, 100, bos);
                FileInputStream fis = new FileInputStream(uploadFile);
                byte[] b = new byte[fis.available()];
                fis.read(b);
                for (int i = 0; i < b.length; i++) {
                    bit = (b[i] & 0x0f0) >> 4;
                    sb.append(chars[bit]);
                    bit = b[i] & 0x0f;
                    sb.append(chars[bit]);
                }

                fis.close();
                String photoFile = uploadFile.getAbsolutePath();
                DownloadPicture.loadThisLocality(photoFile, ((ImageView) linearLayouts.get(position).getChildAt(0)));
                imagsPaths.set(position, sb.toString());
            } catch (IOException e) {
                U.Toast(AddEvalutatActivity.this, e.getLocalizedMessage());
            } finally {
                if (bos != null) {
                    try {
                        bos.flush();
                        bos.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}
